package com.xiong.xtools.citychoose;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Author : 熊文强
 * Time : 2017/9/18
 * Content : 复制数据库文件到本地
 */
public class DBManager {
    private String DB_NAME = "taurus.db";
    private static Context mContext;
    private static SQLiteDatabase database;

    private static DBManager dbManager ;

    private DBManager(Context mContext) {
        this.mContext = mContext;
    }
    public  static  synchronized  DBManager getDBManager(Context mContext){
        if (dbManager==null){
            dbManager=new DBManager(mContext);
        }
        return dbManager;
    }

    //把assets目录下的db文件复制到dbpath下
    public void initDBManager(String packName) {
        String dbPath = "/data/data/" + packName
                + "/" + DB_NAME;
        if (!new File(dbPath).exists()) {
            try {
                FileOutputStream out = new FileOutputStream(dbPath);
                InputStream in = mContext.getAssets().open("taurus.db");
                byte[] buffer = new byte[1024];
                int readBytes = 0;
                while ((readBytes = in.read(buffer)) != -1)
                    out.write(buffer, 0, readBytes);
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
        }
        database = SQLiteDatabase.openOrCreateDatabase(dbPath, null);

    }

    public SQLiteDatabase getDatabase() {
        return database;
    }

}
